using BuildingBlocks.Infrastructure.EventBus;
using Identity.Application.Contracts.Commands;
using Identity.Application.Contracts.Common;
using Identity.Application.Contracts.Events;
using Identity.Application.Contracts.Services;
using Identity.Domain.Aggregates;
using MediatR;

namespace Identity.Application.Permissions.CommandHandler;



public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, Result>
{
    private readonly IUserService _userService;
    private readonly IRoleService _roleService;
    private readonly IUserRoleService _userRoleService;
    private readonly IEventBus _eventBus;

    public RegisterUserCommandHandler(IUserService userService, IRoleService roleService, IUserRoleService userRoleService, IEventBus eventBus)
    {
        _userService = userService;

        _roleService = roleService;

        _userRoleService = userRoleService;

        _eventBus = eventBus;
    }
    public async Task<Result> Handle(RegisterUserCommand request, CancellationToken cancellationToken)
    {
        //检验可行
        var isExistname = await _userService.UserExistsByUserNameAsync(request.Username);
        if (isExistname) return Result.Failure("该用户名已被注册！");

        var isExistmail = await _userService.UserExistsByEmailAsync(request.Email);
        if (isExistmail) return Result.Failure("该邮箱已经注册！");


        var defaultRoleName = "USER";
        var defaultRoleCode = "USer";
        
        if (!await _roleService.RoleExistsByNameAsync(defaultRoleName))
        {
            var userRole = Role.CreateRole(defaultRoleCode, defaultRoleName);
            var actionReslut = await _roleService.CreateRoleAsync(userRole.Id, defaultRoleCode, defaultRoleName, userRole.Description, userRole.Status);
            if (!actionReslut.Succeeded)
                return Result.Failure(actionReslut.Errors);
        }


        //操作聚合根
        var user = UserAggregate.CreateUser(request.Username, request.Email);//创建用户聚合根，触发领域行为

        user.AddRoles(defaultRoleCode);



        //数据同步到AspNetCore.Identity内部
        var result = await _userService.CreateUserAsync(user.Id, user.UserName, user.Email, request.Password);
        if (!result.Succeeded)
            return Result.Failure(result.Errors);

        foreach (var role in user._roles)
        {
            var roledata = await _roleService.GetRoleByNameAsync(role);
            var assingroleResult = await _userRoleService.AssignRoleAsync(user.Id, roledata!.Id);
            if (!assingroleResult.Succeeded)
                return Result.Failure(assingroleResult.Error!);

        }

        //推送事件
        var userRegisteredEvent = new UserRegisteredEvent(user.Id, user.Email);

        await _eventBus.PublishAsync(userRegisteredEvent);

        return Result.Success(
            new
            {
                Message = "注册成功",
                User = new
                {
                    user.Id,
                    user.Email

                }
            });
    }
}
